package main

import (
	"bufio"
	"fmt"
	"log"
	"net/url"
	"os"
	"time"

	"github.com/gorilla/websocket"
)

func main() {
	u := url.URL{Scheme: "ws", Host: "localhost:9000", Path: "/c"} // 假设服务端运行在本地9000端口，使用/c端点
	c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal("Dial Error:", err)
	}
	defer c.Close()

	done := make(chan struct{})

	go func() {
		defer close(done)
		for {
			_, message, err := c.ReadMessage()
			if err != nil {
				log.Println("Read Error:", err)
				return
			}
			fmt.Printf("Received: %s\n", message)
		}
	}()

	inputReader := bufio.NewReader(os.Stdin)
	for {
		fmt.Print("Enter text to send (or 'exit' to quit): ")
		text, err := inputReader.ReadString('\n')
		if err != nil {
			log.Println("Input Error:", err)
			return
		}
		text = text[:len(text)-1] // 去除换行符

		if text == "exit" {
			break
		}

		err = c.WriteMessage(websocket.TextMessage, []byte(text))
		if err != nil {
			log.Println("Write Error:", err)
			return
		}
	}

	c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
	<-done
	time.Sleep(time.Second) // 等待goroutine结束
}
